package com.wj.controller;

import com.hospital.common.pojo.AuditResult;
import com.wj.service.ImageAuditService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/medical")
public class MedicalImageController {

    private final ImageAuditService imageAuditService;

    @Autowired
    public MedicalImageController(ImageAuditService imageAuditService) {
        this.imageAuditService = imageAuditService;
    }

    /**
     * 接收图片文件并进行审核
     */
    @PostMapping("/audit")
    public ResponseEntity<?> auditMedicalImage(
            @RequestParam("imageFile") MultipartFile imageFile,
            @RequestParam(value = "woundType", required = false) String woundType) {

        try {
            // 验证文件类型
            if (!isAllowedImageType(imageFile.getContentType())) {
                return ResponseEntity.badRequest().body(createErrorResponse(
                        AuditResult.ERROR_IMAGE_URL,
                        "仅支持JPG、PNG格式的图片"
                ));
            }

            // 验证文件大小（例如限制为5MB）
            if (imageFile.getSize() > 5 * 1024 * 1024) {
                return ResponseEntity.badRequest().body(createErrorResponse(
                        AuditResult.ERROR_IMAGE_URL,
                        "图片大小不能超过5MB"
                ));
            }

            // 将图片转为Base64
            String base64Image = convertToBase64(imageFile);

            // 构建Base64图片URL格式
            String imageDataUrl = "data:" + imageFile.getContentType() + ";base64," + base64Image;

            // 调用审核服务
            Integer auditResult = imageAuditService.auditByBase64(imageDataUrl, woundType);

            // 返回结果
            if (auditResult == AuditResult.COMPLIANT) {
                return ResponseEntity.ok(createSuccessResponse("图片审核通过"));
            } else if (auditResult == AuditResult.NON_COMPLIANT) {
                return ResponseEntity.badRequest().body(createErrorResponse(
                        auditResult,
                        "图片包含不合规内容，请重新上传"
                ));
            } else {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                        .body(createErrorResponse(
                                auditResult,
                                "图片审核失败: " + AuditResult.getDescription(auditResult)
                        ));
            }

        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse(
                            AuditResult.ERROR_IMAGE_URL,
                            "图片处理失败: " + e.getMessage()
                    ));
        }
    }

    /**
     * 直接通过Base64审核图片
     */
    @PostMapping("/audit-base64")
    public ResponseEntity<?> auditMedicalImageBase64(@RequestBody Map<String, String> payload) {
        String base64Image = payload.get("image");
        String woundType = payload.get("woundType");

        if (base64Image == null || !base64Image.startsWith("data:image/")) {
            return ResponseEntity.badRequest().body(createErrorResponse(
                    AuditResult.ERROR_IMAGE_URL,
                    "无效的Base64图片格式"
            ));
        }

        Integer auditResult = imageAuditService.auditByBase64(base64Image, woundType);

        if (auditResult == AuditResult.COMPLIANT) {
            return ResponseEntity.ok(createSuccessResponse("图片审核通过"));
        } else {
            return ResponseEntity.badRequest().body(createErrorResponse(
                    auditResult,
                    auditResult == AuditResult.NON_COMPLIANT ?
                            "图片包含不合规内容" :
                            AuditResult.getDescription(auditResult)
            ));
        }
    }

    // 辅助方法
    private boolean isAllowedImageType(String contentType) {
        return "image/jpeg".equals(contentType) ||
                "image/png".equals(contentType) ||
                "image/jpg".equals(contentType);
    }

    private String convertToBase64(MultipartFile file) throws IOException {
        return Base64.getEncoder().encodeToString(file.getBytes());
    }

    private Map<String, Object> createSuccessResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("code", AuditResult.COMPLIANT);
        response.put("message", message);
        return response;
    }

    private Map<String, Object> createErrorResponse(int code, String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("code", code);
        response.put("message", message);
        return response;
    }
}
